import sys
import os
import re
import pybedtools
from optparse import OptionParser

from lib import table,barchart
from lib.tools import *

    
usagetxt = "usage: %prog  -a seqCluster_Dir -b  BED_FILE1,BED_FILE2..."
parser = OptionParser(usage=usagetxt, version="%prog 1.0")
parser.add_option("-a", "--afile", dest="afile",
                  help="aligned file in bed format", metavar="FILE")
parser.add_option("-f", "--ffile", dest="ffile",
                  help="fasta file with names like: seq_index_xCOUNTS", metavar="FILE")
parser.add_option("-g", "--gtf",
                   dest="gtf", help="annotate with gtf_file. It will use the 3rd column as the tag to annotate" +
                   "\nchr1    source  intergenic      1       11503   .       +       .       ",metavar="GTF")
parser.add_option("-b", "--bed",
                   dest="bed", help="annotate with bed_file. It will use the 4rd column as the tag to annotate" +
                   "\nchr1    157783  157886  snRNA   0       -",metavar="BED")

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
    
(options, args) = parser.parse_args()

      
if not options.afile:
    print bcolors.FAIL + "-a is a mandatory parameter: alignment file in bed format" + bcolors.ENDC
    parser.print_help()
    sys.exit(1)


if not options.ffile:
    print bcolors.FAIL + "-f is a mandatory parameter: file.fa" + bcolors.ENDC
    parser.print_help()
    sys.exit(1)

if options.bed and options.gtf:
    print bcolors.FAIL + "cannot provide -b and -g at the same time" +  bcolors.ENDC
    parser.print_help()
    sys.exit(1)


####################define variables####################    
samplename=options.ffile.split("/")[-1]
dir_out=options.ffile.replace("/"+samplename,"")
temporalfile=options.ffile+".tt.tmp"
#temporalbedfile=options.ffile+".tt.bed"
#temporalbedann=options.ffile+".ann.bed"
db4js={}
############################################################


############read input files##################################
seq_l=parse_fasta_file(options.ffile)
###############################################################

#####################read aligned sequences#####################
format = what_is(options.afile)
return_obj=parse_align_file(options.afile, seq_l,format)
setclus=return_obj.obj
###############################################################


#merge positions to create clusters: everything connected by positions inthe genome. 
#assumption: minimun number of common loci

a = pybedtools.BedTool(return_obj.bedfile,from_string=True)
c = a.merge(nms=True,d=20,s=True,scores="collapse")

clus_obj=parse_merge_file(c,setclus) #currentClus

####################update clusters according to overlap####################
seqinfo=setclus
setclus=mergeclus(clus_obj,setclus)
############################################################

#####################create sequences overview ####################
setclus=show_seq(setclus,seqinfo)
############################################################

#####################reduce loci when possible#####################
setclus=reduceloci(setclus)
###############################################################

#####################overlap with features###################
bedfile=generate_position_bed(setclus)
a = pybedtools.BedTool(bedfile,from_string=True)
beds=[]
if options.bed:
    list_files=options.bed
    type_ann="bed"
if options.gtf:
    list_files=options.gtf
    type_ann="gtf"

if list_files:
    beds=list_files.split(",")
    for filebed in beds:

        db= os.path.basename(filebed)
        db4js[db]=[0,0,0]
        b = pybedtools.BedTool(filebed)
        c=a.intersect(b, wo=True)
        setclus=anncluster(c,setclus,db,type_ann)            
#############################################################

#####################creating html####################
cmd="mkdir %s" % (dir_out+"/html")
print bcolors.OKBLUE+cmd+bcolors.ENDC 
os.system(cmd)
pathscript=os.path.abspath(__file__).replace("sc-parser-bw.py","")
cmdcp="rsync -a -u --exclude='- *.' "+pathscript+"js "+pathscript+"css "+pathscript+"images "+dir_out+"/html/."
print bcolors.OKBLUE+cmdcp+bcolors.ENDC 
os.system(cmdcp)

chtml = open(dir_out+"/html/clus.html", 'w')
ihtml = open(dir_out+"/html/info.html", 'w')
dbhtml = open(dir_out+"/html/annotation.html", 'w')
ccont=table.make_cell_header("id")+table.make_cell_header("frequency")+table.make_cell_header("DB")
ccont=table.make_header(ccont)
icont=""

#####################creating plain text files#####################
out = open(dir_out+"/clus.parse.txt", 'w')
#outtemp = open(temporalfile, 'w')
outbed=dir_out+"/clus.bed"

db4js["None"]=[0,0,0]
for id in setclus.keys():
    dbsummary=""
    #if (int(id)!=0):
    clus=setclus[id]
    if (len(clus.members)>0):
        cluster_id="C:%s" % id
        ccell=table.make_cell_link(cluster_id,"info.html#C:%s" % id)
        contentDivC=table.make_div(table.make_a("<b>"+cluster_id+"</b>",cluster_id),"clus","css_id")
        out.write("C %s\n" % id)
        numloci=0
        numlocidb=init_numlocidb(beds)
        exp=0
        #seq_header="".join(map(table.make_cell_header,table.HEADER_SEQ))
        #print seq_header
        #contentDivS=table.make_header(seq_header)
        for seq in clus.members:
            exp+=int(seq.freq)
        #    contentDivS+=table.make_line("".join(map(table.make_cell,[seq.seq,seq.freq,seq.len])))
            out.write("S %s %s %s %s\n" % (seq.seq,seq.freq,seq.len,seq.pos))
        ccell+=table.make_cell(exp)
        contentDivC+=table.make_div("<pre>"+clus.showseq+"</pre>","seqs","css_seqs")

        contentDivL=table.make_header("".join(map(table.make_cell_header,table.HEADER_L)))
        for idl in clus.loci.keys():
            tpos=clus.loci[idl]
            numloci+=1
            out.write("L %s %s %s %s %s\n" % (tpos.idl,tpos.chr,tpos.start,tpos.end,tpos.strand))
            #outtemp.write("%s\t%s\t%s\t%s\t%s\t%s\n" %  (tpos.chr,tpos.start,tpos.end,id,0,tpos.strand))
            idl=int(tpos.idl)
            contentA=""
            for db in clus.dbann.keys():
                #print "DBA %s" % (db)
                tdb=clus.dbann[db]
                if (tdb.ann.has_key(idl)):
                    ann=tdb.ann[idl]
                    numlocidb[db]+=1
                    contentA+="%s(%s %s)-(%s,%s);" % (ann.db,ann.name,ann.strand,ann.to5,ann.to3);
                    out.write("A %s %s %s %s %s\n" % (ann.db,ann.name,ann.strand,ann.to5,ann.to3))
                    #print result for consistent DB
            pos="%s:%s-%s %s" % (tpos.chr,tpos.start,tpos.end,tpos.strand)
            contentDivL+=table.make_line("".join(map(table.make_cell,[pos,contentA])))
        contentDivC+=table.make_div(table.make_table(contentDivL,"loci"),"loci","css_loci")
        cons=0
        ann=0
        tmp_db4js={}
        for filebed in beds:
            db= os.path.basename(filebed)
            ratio=1.0*numlocidb[db]/numloci

            #tmp_db4js[db]=0
            
            out.write("DBstat %s %s %s %s \n" % (db,numloci,numlocidb[db],ratio))
            
            if (numlocidb[db]>0):
                ann=1
                tmp_db4js[db]=1
                if(ratio>=0.33):
                    out.write("DB %s %s %s consistent\n" % (db,numloci,numlocidb[db]))
                    dbsummary+="DB(%s) %s/%s consistent;" % (db,numlocidb[db],numloci)
                    cons+=1
                    
                elif (ratio<0.33):
                   
                    out.write("DB %s %s %s no-consistent\n" % (db,numloci,numlocidb[db]))
                    dbsummary+="DB(%s) %s/%s consistent;" % (db,numlocidb[db],numloci)

        for db in tmp_db4js:
            if cons==0: 
                db4js[db][2]+=exp
            if cons>1: 
                db4js[db][1]+=exp
            if cons==1: 
                db4js[db][0]+=exp

        if (ann==0): 
            db4js["None"][0]+=exp

        ccell+=table.make_cell(dbsummary)
        ccont+=table.make_line(ccell)
        icont+=table.make_div(contentDivC,cluster_id,"css_clus")
        #idiv=make_div(clus,clus,"cluster")
listbar=[]
for db in db4js.keys():
    listbar.append({"args":db,"unique":db4js[db][0],"multiple":db4js[db][1],"unconsistently":db4js[db][2]})
listkeys=["unique","multiple","unconsistently"]

dbhtml.write(barchart.createhtml(listbar,listkeys))
dbhtml.close()
ccont=table.make_table(ccont,samplename)
ccont=table.make_jshtml(ccont,samplename)         
chtml.write(ccont)
chtml.close()
icont=table.make_html(icont,samplename)         
ihtml.write(icont)
ihtml.close()
out.close()
#outtemp.close() 
############################################################

####################data for genome browser####################
#cmd2intersect="mergeBed -s -nms -i %s > %s" % (temporalfile,temporalbedfile)
#print bcolors.OKBLUE+cmd2intersect+bcolors.ENDC
#os.system(cmd2intersect)

#header="track name=%(name)s description='%(name)s' " % {'name':samplename}
#cmd2intersect="echo '%s';awk '{print $1,$2,$3,$4,$5,$5 }'  %s | sed 's/ /\t/g'> %s " % (header,temporalbedfile,outbed)
#print bcolors.OKBLUE+cmd2intersect+bcolors.ENDC
#os.system(cmd2intersect)

############################################################





